<template>
  <el-upload action :show-file-list="false" :before-upload="beforeExcelUpload" :accept="accept">
    <a href="javascript:;">批量导入</a>
  </el-upload>
</template>

<script>
export default {
  props: {
    accept: {
      type: String,
      default: '.xls,.xlsx,.txt',
    },
  },
  data() {
    return {}
  },
  methods: {
    getData(data) {
      this.$emit('callback', data)
    },

    beforeExcelUpload(file) {
      // 大小限制
      if (file.size / 1024 / 1024 > 2) {
        this.$message.warning('上传的excel表格不能超过2M')
        return false
      }
      // 文件格式限制
      if (!/(\.xls$|\.xlsx$|\.txt$)/.test(file.name)) {
        this.$message.warning('请上传正确的excel格式文件')
        return false
      }
      this.fileName = file.name
      this.fileSize = (file.size / 1024).toFixed(1) + 'KB'
      // 读取excel文件数据
      this.importExcelData(file)
      return false
    },

    // 读取文件
    importExcelData(file) {
      let _this = this
      var rABS = false //是否将文件读取为二进制字符串
      var reader = new FileReader()
      let limit = 201
      FileReader.prototype.readAsBinaryString = function (file) {
        let binary = ''
        let wb //读取完成的数据
        let outdata
        let reader = new FileReader()
        reader.onload = function (e) {
          let bytes = new Uint8Array(reader.result)
          let length = bytes.byteLength
          for (let i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i])
          }
          if (file.type == 'text/plain') {
            outdata = binary.split(/[\n]/)
            outdata.forEach(item => {
              item = item.trim()
              item = item.replace(/[\s\r\n\r]+/g, '')
            })
            outdata = outdata
              .filter(item => {
                return item && item.trim() && /\d+/g.test(item)
              })
              .slice(0, limit)
            _this.getData(outdata || [])
          } else {
            let XLSX = require('xlsx')
            wb = XLSX.read(binary, {
              type: 'binary',
            })
            outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]) //outdata就是你想要的东西
            // if (outdata.length > 500) {
            //   _this.$message.warning("导入数据不能超过500条");
            //   return;
            // }
            // if (_this.excelType === "addr") {
            //   _this.manageAddrExcelData(outdata);
            // } else if (_this.excelType === "name") {
            //   _this.manageNameExcelData(outdata);
            // } else if (_this.excelType === "phone") {
            _this.managePhoneExcelData(outdata)
            // }
          }
        }
        reader.readAsArrayBuffer(file)
      }
      if (rABS) {
        reader.readAsArrayBuffer(file)
      } else {
        reader.readAsBinaryString(file)
      }
    },
    managePhoneExcelData(excelData) {
      if (excelData.length > 0) {
        let key = Object.keys(excelData[0])[0]
        let data = {}
        let normalList = []
        let errorList = []
        data[key] = key
        excelData.unshift(data)
        excelData.forEach((item, index) => {
          let normalFlag = true
          let phoneItem = {
            phone: (function (item) {
              if (!item['电话号码']) {
                item['电话号码'] = item[key]
                item['电话号码'] = item['电话号码'] + ''
              }
              // error超过25个字符
              if (item['电话号码'] && item['电话号码'].length > 25) {
                normalFlag = false
                return item['电话号码'] + 'error' + (index + 2) + 'error超过25个字符'
              }
              // 不能有汉字
              if (item['电话号码'] && new RegExp('[\\u4E00-\\u9FFF]+', 'g').test(item['电话号码'])) {
                normalFlag = false
                return item['电话号码'] + 'error' + (index + 2) + 'error不能有汉字'
              }
              // error不能有字母
              if (item['电话号码'] && new RegExp('[a-zA-Z]', 'g').test(item['电话号码'])) {
                normalFlag = false
                return item['电话号码'] + 'error' + (index + 2) + 'error不能有字母'
              }
              return item['电话号码'] ? item['电话号码'] : ''
            })(item),
          }
          if (item['电话号码']) {
            if (normalFlag) {
              normalList.push(phoneItem.phone)
            } else {
              errorList.push(phoneItem.phone)
            }
          }
        })
        this.getData(normalList || [])
      }
    },
  },
}
</script>

<style lang="less" scoped>
a {
  color: #409eff;
  white-space: nowrap;
}
</style>
